const fs = require("fs");
const session = require("express-session");
const express = require("express");
const app = express();
app.listen(3000, () => {
    console.log("服务已启动");
});
app.use(
    session({
        secret: "asdfadfadf", // 加密字符串
        saveUninitialized: true,
        resave: true,
    })
);
app.get("/index.html", (req, res) => {
    if (req.session.isLogin != "abc") {
        res.send(
            '<script>alert("请先登录"); location.href="/login.html";</script>'
        );
        return;
    }
    fs.readFile("./public/index.html", "utf-8", (err, data) => {
        let title = "咏鹅";
        let author = "骆宾王";
        let content = "鹅鹅鹅，曲项向天歌。";

        data = data.replace("{{title}}", title);
        data = data.replace("{{author}}", author);
        data = data.replace("{{content}}", content);

        res.send(data);
    });
});

app.get("/login.html", (req, res) => {
    fs.readFile("./public/login.html", "utf-8", (err, data) => {
        res.send(data);
    });
});

app.use(express.urlencoded({ extended: false }));
app.post("/api/login", (req, res) => {
    console.log(req.body.username, req.body.password, req.body);
    if (req.body.username == "admin" && req.body.password == "123") {
        req.session.isLogin = "abc";
        req.session.username = "老汤";
        res.send({ status: 200, msg: "登录成功" });
    } else {
        res.send({ status: 500, msg: "登录失败" });
    }
});